package com.example.todosync.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.core.userdetails.InMemoryUserDetailsManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Value("${app.security.users:}")
    private String usersProp;

    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        List<UserDetails> users = new ArrayList<>();
        if (usersProp == null || usersProp.trim().isEmpty()) {
            users.add(User.withUsername("user").password("{noop}password").roles("USER").build());
        } else {
            for (String pair : usersProp.split(",")) {
                String[] parts = pair.trim().split(":");
                if (parts.length == 2) {
                    String username = parts[0].trim();
                    String password = parts[1].trim();
                    users.add(User.withUsername(username).password("{noop}" + password).roles("USER").build());
                }
            }
            if (users.isEmpty()) {
                users.add(User.withUsername("user").password("{noop}password").roles("USER").build());
            }
        }
        return new InMemoryUserDetailsManager(users);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors() // 使用 WebMvcConfigurer 定义的 CORS
            .and()
            .authorizeRequests()
                .antMatchers("/sync/**").authenticated()
                .anyRequest().permitAll()
            .and()
            .httpBasic();
        return http.build();
    }
}